const block = require('../blockChain/app/javascripts/app');

DenCarToken = block.DenCarToken;

var query = {
    getInfo: function(address)  {
        console.log(address);
        var balance = web3.fromWei(web3.eth.getBalance(address));
        // var denCar;
        // var dct;
        // DenCarToken.deployed().then(function(instance) {
        //     dct = instance;
        //     return dct.getBalance.call(address, {from: account});
        // }).then(function(value) {
        //     exports.denCar = value;
        // }).catch(function(e) {
        //     console.log(e);
        //     self.setStatus("Error getting balance; see log.");
        // });
        var data = [{
            address: address,
            balance: balance
        }];
        return data;

    },
    getDenCarBalance: async function (address) {
        var balance = await block.getDenCarBalance(address);
        return balance;
    },
    buyToken:async function (address,amount) {

        amount = parseInt(amount);

        var dct;
        DenCarToken.deployed().then(function(instance) {
            dct = instance;
            var data = "0xa6f2ae3a"; // must set data which contain the hash of function name

            var trans = {"from":address,"to":dct.address,"value":web3.toWei(amount,"ether"),"data":data};
            web3.eth.sendTransaction(trans);


        });
    },
    //这是Blockchain.js里的用户间发送代币函数，外部调用此功能
    sendToken:async function (fromAddress,toAddress,amount) {

        amount = parseInt(amount);

        var dct;
        //这里调用blockChain文件夹里的函数，
        DenCarToken.deployed().then(function(instance) {  //检查合约是否已经部署
            dct = instance;  //获取合约实例
            return dct.transfer(toAddress, amount, {from: fromAddress}); //合约.transfer  发送代币
        }).catch(function(e) {
        console.log(e);

        });
    },
    getNextAddress: function(id)  {
        console.log(block.accounts[id]);
        return block.accounts[id];
    },
    UserRegister: function(name,phone,account) {

    var dct;
    DenCarToken.deployed().then(function(instance) {

      dct = instance;
      // var name = web3.toHex(name);
      var phone = parseInt(phone);
      dct.userRegister(name,phone ,{from: account});
    }).then(function() {

        console.log("OK!");
    }).catch(function(e) {
      console.log(e);
      self.setStatus("Error sending coin; see log.");
    });
  },


}

module.exports = {
    'POST /api/getInfo': async (ctx, next) => {
        // 设置Content-Type:
        ctx.response.type = 'application/json';
        // 设置Response Body:
        ctx.response.body = {
            data: query.getInfo(ctx.request.body.address)
        };
    },
    query
}